package com.dudu.timer;

import java.io.StringWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dudu.bean.ReportDailyAbilityBean;
import com.dudu.bean.ReportDailyActiveBean;
import com.dudu.bean.ReportDailyBean;
import com.dudu.bean.ReportDailyNewBean;
import com.dudu.dao.DailyReportDao;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.DictionaryUtils;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.EmailSend;

/**
 * 嘟一下日报表
 * 统计嘟一下前一天的新增客户数、活跃客户数、活跃用户数、通话次数、通话时长数据，发送邮件至相关邮箱
 * @author jack
 * @time 2016-08-02
 */
public class EmailSendToYunYingJob implements Job {
	//log日志
	public static final Logger log = core.util.Logger.getLogger(EmailSendToYunYingJob.class.getName());
	//数据库连接
	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	//日报表dao
	private DailyReportDao dailyReportDao = new DailyReportDao();
	//运营平台地址
	private IOperationPlatformService operationPlatformServiceImpl = new OperationPlatformServiceImpl();

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		log.info("执行嘟一下日报表job");
		try{		
			String emailAdressStr = DictionaryUtils.getValueByTypeAndKey("report_email", "email");	//获得日报表接收邮箱
			if(StringUtils.isNotBlank(emailAdressStr)){			
				StringBuffer content = new StringBuffer();	//邮件内容
				String yestoday = DateUtils.getYestodayByFormat();	//日期格式yyyy-MM-dd
				String beginTime = DateUtils.getTimeAddBeginStr(yestoday);  //格式"2016-08-02 00:00:00"
				String endTime = DateUtils.getTimeAddEndStr(yestoday); 		//格式"2016-08-02 23:59:59"	
				JSONArray appArray = queryAppList();	//查询所有的APP
				
				//日总消耗统计报表
				this.reportDailyTotal(content, beginTime, endTime);
				//应用消耗日统计报表
				this.reportDailyByApp(content, beginTime, endTime, appArray);
				//通道商消耗量日统计报表
				this.reportDailyByProduct(content, beginTime, endTime);
				//活跃数日统计
				this.reportDailyActive(content, beginTime, endTime, appArray);
				//新增注册数日统计
				this.reportDailyNew(content, yestoday);
				String[] emailAdressArray = emailAdressStr.split(",");
				
				for(String emailAdress:emailAdressArray){
					Thread.sleep(1000*10); //邮件服务器不支持连续发送
					EmailSend.sendMail(emailAdress, "嘟嘟日报表" + yestoday, content.toString(), null, null); //发送邮件
				}
				
			}else{
				log.info("未配置日报表接收邮件地址");
			}
		}catch(Exception ex){
			ex.getMessage();
			log.info("嘟一下日报表error");
		}
	}
	
	/**
	 * 日总消耗：分钟、条数
	 * @param content
	 * @param beginTime
	 * @param endTime
	 */
	private void reportDailyTotal(StringBuffer content, String beginTime, String endTime) {
		if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)){	
			List<ReportDailyAbilityBean> reportDailyBeanList = new ArrayList<ReportDailyAbilityBean>();	
			List<JSONObject> dataList = this.dailyReportDao.queryProductByTime(coreDao, beginTime, endTime);
			if(dataList != null){
				Integer totalFen = 0; //总分钟数
				Integer totalTiao = 0; //总条数
				for(int j=0;j<dataList.size();j++){
					JSONObject data = dataList.get(j);
					String totalTime = data.optString("total_time");
					String unit = data.optString("unit");
					if("分钟".equals(unit)){
						totalFen = totalFen + Integer.valueOf(totalTime);
					}else if("条".equals(unit)){
						totalTiao = totalTiao + Integer.valueOf(totalTime);
					}
					

				}
				ReportDailyAbilityBean reportDailyBean = new ReportDailyAbilityBean();
				reportDailyBean.setRequestCount(totalFen.toString()); //分钟
				reportDailyBean.setTotalTime(totalTiao.toString()); //条数
				reportDailyBeanList.add(reportDailyBean);
			}
			
			try {			
				String reportDailyContent = getTempleteContent("vm/reportDailyTotal.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				log.info("日总消耗统计报表渲染模板error");
			}
		}
	}
	
	/**
	 * 查询APP列表
	 * @param 1：一页
	 * @param 200: 200行数据
	 * @return
	 */
	private JSONArray queryAppList(){
		IOperationPlatformService OperationPlatformServiceImpl = new OperationPlatformServiceImpl();
		return OperationPlatformServiceImpl.queryAppItems("", "", "", 1, 200).optJSONArray("data");
	}
	
	/**
	 * 应用消耗日统计报表
	 * @param content
	 * @param yestoday
	 */
	private void reportDailyByApp(StringBuffer content, String beginTime, String endTime, JSONArray appArray) {
		if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime) && appArray!=null){	
			List<ReportDailyBean> reportDailyBeanList = new ArrayList<ReportDailyBean>();	
			for(int i=0; i<appArray.size(); i++){
				JSONObject appJson = appArray.getJSONObject(i);
				String isvName = appJson.optString("isv_name");
				String appName = appJson.optString("app_name");
				String appKey = appJson.optString("app_key");
				
				List<JSONObject> dataList = this.dailyReportDao.queryByAppAndTime(coreDao, appKey, beginTime, endTime);
				if(dataList != null){
					for(int j=0;j<dataList.size();j++){
						JSONObject data = dataList.get(j);
						String productCode = data.optString("product_code");
						String requestCount = data.optString("request_count");
						String totalTime = data.optString("total_time");
						String unit = data.optString("unit");
						
						/**
						 * 针对语音通知、短信、ivr统计发起次数
						 */
						if("VOICE".equals(productCode) || "VOICEBATCH".equals(productCode) 
								|| "VOICE70".equals(productCode) || "VOICE140".equals(productCode)
								|| "SMMS".equals(productCode) || "IVVR".equals(productCode)){
							requestCount = String.valueOf(this.dailyReportDao.queryRequestTime(coreDao, appKey, productCode, null, beginTime, endTime));
						}
						
						ReportDailyBean reportDailyBean = new ReportDailyBean();
						reportDailyBean.setAppName(appName);
						reportDailyBean.setIsvName(isvName);
						reportDailyBean.setProductName(this.converProductCodeToName(productCode));
						reportDailyBean.setRequestCount(requestCount);
						reportDailyBean.setTotalTime(totalTime);
						reportDailyBean.setUnit(unit);
						reportDailyBeanList.add(reportDailyBean);
					}
				}
			}
			
			Collections.sort(reportDailyBeanList);
			 
			try {			
				String reportDailyContent = getTempleteContent("vm/reportDailyApp.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				log.info("应用消耗日统计报表渲染模板error");
			}
		}
	}
	
	/**
	 * 通道商消耗量日统计报表
	 * @param content
	 * @param beginTime
	 * @param endTime
	 */
	private void reportDailyByProduct(StringBuffer content, String beginTime, String endTime) {
		if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)){	
			List<ReportDailyAbilityBean> reportDailyBeanList = new ArrayList<ReportDailyAbilityBean>();	
			List<JSONObject> dataList = this.dailyReportDao.queryProductByTime(coreDao, beginTime, endTime);
			if(dataList != null){
				for(int j=0;j<dataList.size();j++){
					JSONObject data = dataList.get(j);
					String productSubCode = data.optString("product_subcode");
					String requestCount = data.optString("request_count");
					String totalTime = data.optString("total_time");
					String unit = data.optString("unit");
					String abilityName = this.converProductSubCodeToAbilityName(productSubCode);
					String productName = this.converProductSubCodeToName(productSubCode);
					
					/**
					 * 针对语音通知、短信、ivr统计发起次数
					 */
					if(productSubCode.contains("Voice") || productSubCode.contains("Audeo") 
							|| productSubCode.contains("SMS") || productSubCode.contains("Ivr")){
						requestCount = String.valueOf(this.dailyReportDao.queryRequestTime(coreDao, null, null, productSubCode, beginTime, endTime));
					}
					
					/**
					 * 针对多方通话统计三方及三方以上的发起数量
					 */
					if("TalksV2".equals(productSubCode)){
						List<JSONObject> calledMoreThanOneCountList = this.dailyReportDao.queryCalledMoreThanOneByTime(coreDao, beginTime, endTime); //查询被叫超过1人的次数
						if(calledMoreThanOneCountList.size()>0){
							JSONObject calledMoreThanOneCountJson = calledMoreThanOneCountList.get(0);
							String amount = calledMoreThanOneCountJson.optString("amount"); //请求次数
							String time = calledMoreThanOneCountJson.optString("total_time"); //消耗时长
							
							ReportDailyAbilityBean reportDailyBean = new ReportDailyAbilityBean();
							reportDailyBean.setAbilityName(abilityName);
							reportDailyBean.setProductName(productName+"(三方及三方以上)");
							reportDailyBean.setRequestCount(amount);
							reportDailyBean.setTotalTime(time);
							reportDailyBean.setUnit(unit);
							reportDailyBeanList.add(reportDailyBean);
							
							requestCount = String.valueOf(Integer.valueOf(requestCount) - Integer.valueOf(amount));
							totalTime = String.valueOf(Integer.valueOf(totalTime) - Integer.valueOf(time));
							productName = productName + "(两方)"; 
						}
					}
					
					ReportDailyAbilityBean reportDailyBean = new ReportDailyAbilityBean();
					reportDailyBean.setAbilityName(abilityName);
					reportDailyBean.setProductName(productName);
					reportDailyBean.setRequestCount(requestCount);
					reportDailyBean.setTotalTime(totalTime);
					reportDailyBean.setUnit(unit);
					reportDailyBeanList.add(reportDailyBean);
				}
			}
			
			Collections.sort(reportDailyBeanList);
			
			try {			
				String reportDailyContent = getTempleteContent("vm/reportDailyAbility.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				log.info("通道商消耗量日统计报表渲染模板error");
			}
		}
	}
	
	/**
	 * 活跃数日统计
	 * @param content
	 * @param beginTime
	 * @param endTime
	 * @param appArray
	 */
	private void reportDailyActive(StringBuffer content, String beginTime, String endTime, JSONArray appArray) {
		if(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime) && appArray!=null){	
			List<ReportDailyActiveBean> reportDailyBeanList = new ArrayList<ReportDailyActiveBean>();	
			for(int i=0; i<appArray.size(); i++){
				JSONObject appJson = appArray.getJSONObject(i);
				String isvName = appJson.optString("isv_name");
				String appName = appJson.optString("app_name");
				String appKey = appJson.optString("app_key");
				
				List<JSONObject> dataList = this.dailyReportDao.queryActiveByAppAndTime(coreDao, appKey, beginTime, endTime);
				if(dataList != null){
					for(int j=0;j<dataList.size();j++){
						JSONObject data = dataList.get(j);
						String productCode = data.optString("product_code");
						String activeCompany = data.optString("activeCompany");
						String activeUser = data.optString("activeUser");
						ReportDailyActiveBean reportDailyBean = new ReportDailyActiveBean();
						reportDailyBean.setAppName(appName);
						reportDailyBean.setIsvName(isvName);
						reportDailyBean.setProductName(this.converProductCodeToName(productCode));
						reportDailyBean.setActiveCompany(activeCompany);
						reportDailyBean.setActiveUser(activeUser);
						reportDailyBeanList.add(reportDailyBean);
					}
				}
			}
			
			Collections.sort(reportDailyBeanList);
			
			try {			
				String reportDailyContent = getTempleteContent("vm/reportDailyActive.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				log.info("活跃数日统计报表渲染模板error");
			}
		}
	}
	
	/**
	 * 新增注册数日统计
	 * @param content
	 * @param yestoday
	 */
	private void reportDailyNew(StringBuffer content, String yestoday) {
		if(StringUtils.isNotBlank(yestoday)){	
			List<ReportDailyNewBean> reportDailyBeanList = new ArrayList<ReportDailyNewBean>();	
			List<JSONObject> dataList = this.operationPlatformServiceImpl.queryRegisterNum(yestoday);
			if(dataList != null){
				for(int j=0;j<dataList.size();j++){
					JSONObject data = dataList.get(j);
					String isvName = data.optString("isv_name");
					String appName = data.optString("app_name");
					String newCompany = data.optString("cust_register_num");
					String newUser = data.optString("user_register_num");
					
					ReportDailyNewBean reportDailyBean = new ReportDailyNewBean();
					reportDailyBean.setIsvName(isvName);
					reportDailyBean.setAppName(appName);
					reportDailyBean.setNewCompany(newCompany);
					reportDailyBean.setNewUser(newUser);
					reportDailyBeanList.add(reportDailyBean);
				}
			}
			
			Collections.sort(reportDailyBeanList);
			
			try {			
				String reportDailyContent = getTempleteContent("vm/reportDailyNew.vm", reportDailyBeanList);
				content.append(reportDailyContent); 					
			} catch (Exception e) {
				log.info("活跃数日统计报表渲染模板error");
			}
		}
	}
	
	/**
	 * 产品编码和名称的转换
	 * @param productCode
	 * @return
	 */
	private String converProductCodeToName(String productCode){
		String productName = "";
		if("MPTY".equals(productCode)){
			productName = "多方通话";
		}else if("DIAL".equals(productCode)){
			productName = "两方通话";
		}else if("VOICE".equals(productCode)){
			productName = "语音通知";
		}else if("VOICEBATCH".equals(productCode)){
			productName = "语音通知(批量)";
		}else if("VCAPTCHA".equals(productCode)){
			productName = "语音验证码";
		}else if("SMMS".equals(productCode)){
			productName = "短信";
		}else if("ADSMMS".equals(productCode)){
			productName = "营销短信";
		}else if("CALLRECORDER".equals(productCode)){
			productName = "录音";
		}else if("IVVR".equals(productCode)){
			productName = "语音调研";
		}else if("VOICE70".equals(productCode)){
			productName = "70字语音套餐产品";
		}else if("VOICE140".equals(productCode)){
			productName = "140字语音套餐产品";
		}
		return productName;
	}
	
	/**
	 * 二级产品编码和名称的转换
	 * @param productSubCode
	 * @return
	 */
	private String converProductSubCodeToName(String productSubCode){
		String productName = "";
		if("TalksV2".equals(productSubCode)){
			productName = "多方通话";
		}else if("ScheduleConference".equals(productSubCode)){
			productName = "专业会议";
		}else if("Dial".equals(productSubCode)){
			productName = "两方通话";
		}else if("Dial_ronglian".equals(productSubCode)){
			productName = "两方通话";
		}else if("Dial_tianyi".equals(productSubCode)){
			productName = "两方通话";
		}else if("Dial_chengqi".equals(productSubCode)){
			productName = "两方通话";
		}else if("Dial_YonYou".equals(productSubCode)){
			productName = "两方通话";
		}else if("VCAPTCHA".equals(productSubCode)){
			productName = "语音验证码";
		}else if("BaiWuSMS".equals(productSubCode)){
			productName = "短信";
		}else if("MCADSMS".equals(productSubCode)){
			productName = "营销短信";
		}else if("WWADSMS".equals(productSubCode)){
			productName = "营销短信";
		}else if("MCSMS".equals(productSubCode)){
			productName = "短信";
		}else if("WWSMS".equals(productSubCode)){
			productName = "短信";
		}else if("VoiceNotice3".equals(productSubCode)){
			productName = "语音通知(文字)";
		}else if("RongLianVoice".equals(productSubCode)){
			productName = "语音通知(文字)";
		}else if("TianYiVoice".equals(productSubCode)){
			productName = "语音通知(文字)";
		}else if("YonYouVoice".equals(productSubCode)){
			productName = "语音通知(文字)";
		}else if("TianRunVoice".equals(productSubCode)){
			productName = "语音通知(文字)";
		}else if("AudeoSend".equals(productSubCode)){
			productName = "语音通知(录音)";
		}else if("RongLianAudeo".equals(productSubCode)){
			productName = "语音通知(录音)";
		}else if("TianYiAudeo".equals(productSubCode)){
			productName = "语音通知(录音)";
		}else if("YonYouAudeo".equals(productSubCode)){
			productName = "语音通知(录音)";
		}else if("Vcaptcha".equals(productSubCode)){
			productName = "语音验证码";
		}else if("Ivr_Ims".equals(productSubCode)){
			productName = "语音调研";
		}else if("Ivr_RongL".equals(productSubCode)){
			productName = "语音调研";
		}else if("Ivr_TianYi".equals(productSubCode)){
			productName = "语音调研";
		}else if("Ivr_YonYou".equals(productSubCode)){
			productName = "语音调研";
		}else if("TianYiVoice70".equals(productSubCode)){
			productName = "语音通知(70字文字)";
		}else if("TianYiVoice140".equals(productSubCode)){
			productName = "语音通知(140字文字)";
		}else if("TianYiAudeo70".equals(productSubCode)){
			productName = "语音通知(70字录音)";
		}else if("TianYiAudeo140".equals(productSubCode)){
			productName = "语音通知(140字录音)";
		}else if("YonYouVoice70".equals(productSubCode)){
			productName = "语音通知(70字文字)";
		}else if("YonYouVoice140".equals(productSubCode)){
			productName = "语音通知(140字文字)";
		}else if("YonYouAudeo70".equals(productSubCode)){
			productName = "语音通知(70字录音)";
		}else if("YonYouAudeo140".equals(productSubCode)){
			productName = "语音通知(140字录音)";
		}else if("RongLianVoice70".equals(productSubCode)){
			productName = "语音通知(70字文字)";
		}else if("RongLianVoice140".equals(productSubCode)){
			productName = "语音通知(140字文字)";
		}else if("RongLianAudeo70".equals(productSubCode)){
			productName = "语音通知(70字录音)";
		}else if("RongLianAudeo140".equals(productSubCode)){
			productName = "语音通知(140字录音)";
		}else if("TianRunVoice70".equals(productSubCode)){
			productName = "语音通知(70字文字)";
		}else if("TianRunVoice140".equals(productSubCode)){
			productName = "语音通知(140字文字)";
		}else if("CallRecorder".equals(productSubCode)){
			productName = "录音";
		}else{
			productName = productSubCode;
		}
		return productName;
	}
	
	/**
	 * 产品编码和名称的转换
	 * @param productSubCode
	 * @return
	 */
	private String converProductSubCodeToAbilityName(String productSubCode){
		String productName = "";
		if("TalksV2".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("ScheduleConference".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("Dial".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("Dial_ronglian".equals(productSubCode)){
			productName = "容联";
		}else if("Dial_tianyi".equals(productSubCode)){
			productName = "天亿";
		}else if("Dial_chengqi".equals(productSubCode)){
			productName = "承启通";
		}else if("Dial_YonYou".equals(productSubCode)){
			productName = "自建通道";
		}else if("VCAPTCHA".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("BaiWuSMS".equals(productSubCode)){
			productName = "百悟";
		}else if("MCADSMS".equals(productSubCode)){
			productName = "名传";
		}else if("MCSMS".equals(productSubCode)){
			productName = "名传";
		}else if("WWADSMS".equals(productSubCode)){
			productName = "微网通";
		}else if("WWSMS".equals(productSubCode)){
			productName = "微网通";
		}else if("VoiceNotice3".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("RongLianVoice".equals(productSubCode)){
			productName = "容联";
		}else if("TianYiVoice".equals(productSubCode)){
			productName = "天亿";
		}else if("YonYouVoice".equals(productSubCode)){
			productName = "自建通道";
		}else if("AudeoSend".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("RongLianAudeo".equals(productSubCode)){
			productName = "容联";
		}else if("TianYiAudeo".equals(productSubCode)){
			productName = "天亿";
		}else if("YonYouAudeo".equals(productSubCode)){
			productName = "自建通道";
		}else if("Vcaptcha".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("Ivr_Ims".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("CallRecorder".equals(productSubCode)){
			productName = "福建电信IMS";
		}else if("Ivr_YonYou".equals(productSubCode)){
			productName = "自建通道";
		}else if("Ivr_RongL".equals(productSubCode)){
			productName = "容联";
		}else if("Ivr_TianYi".equals(productSubCode)){
			productName = "天亿";
		}else if("TianYiVoice70".equals(productSubCode)){
			productName = "天亿";
		}else if("TianYiVoice140".equals(productSubCode)){
			productName = "天亿";
		}else if("TianYiAudeo70".equals(productSubCode)){
			productName = "天亿";
		}else if("TianYiAudeo140".equals(productSubCode)){
			productName = "天亿";
		}else if("YonYouVoice70".equals(productSubCode)){
			productName = "自建通道";
		}else if("YonYouVoice140".equals(productSubCode)){
			productName = "自建通道";
		}else if("YonYouAudeo70".equals(productSubCode)){
			productName = "自建通道";
		}else if("YonYouAudeo140".equals(productSubCode)){
			productName = "自建通道";
		}else if("TianRunVoice70".equals(productSubCode)){
			productName = "天润";
		}else if("TianRunVoice140".equals(productSubCode)){
			productName = "天润";
		}else if("RongLianVoice70".equals(productSubCode)){
			productName = "容联";
		}else if("RongLianVoice140".equals(productSubCode)){
			productName = "容联";
		}else if("RongLianAudeo70".equals(productSubCode)){
			productName = "容联";
		}else if("RongLianAudeo140".equals(productSubCode)){
			productName = "容联";
		}else if("TianRunVoice".equals(productSubCode)){
			productName = "天润融通";
		}else{
			productName = productSubCode;
		}
		return productName;
	}

	/**
	 * 解析模板
	 * @param templete
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "deprecation", "rawtypes" })
	public static String getTempleteContent(String templete, List list) throws Exception {
		StringWriter writer = null;
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource("");
			String realPath = url.getPath();
			VelocityEngine ve = new VelocityEngine();
			Properties p = new Properties();
			p.put(Velocity.FILE_RESOURCE_LOADER_PATH, URLDecoder.decode(realPath));
			ve.init(p);
			Template t = ve.getTemplate(templete, "UTF-8");
			VelocityContext context = new VelocityContext();
			context.put("array", list);
			writer = new StringWriter();
			t.merge(context, writer);
		} catch (Exception e) {
			log.info("<===获得模板出错==>");
			e.printStackTrace();
			throw e;
		}
		return writer.toString();
	}

	public static void main(String[] args) {

	}

}
